<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>欢迎页面</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #FFEEF7;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
            background: #FFF;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }

        input[type="email"],
        input[type="password"],
        input[type="text"],
        textarea {
            width: calc(100% - 20px);
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #FFFAFA;
        }

        button {
            width: 100%;
            padding: 10px;
            background-color: #FF69B4;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #FF1493;
        }

        p {
            text-align: center;
            color: #666;
        }

        #message {
            color: #FF0000;
            text-align: center;
            margin-bottom: 20px;
        }

        a {
            color: #FF69B4;
            text-decoration: none;
            font-weight: bold;
        }

        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div id="message"></div>
<button id="btnUserInfo">个人信息</button>
<button id="btnOrdersInfo">订单信息</button>
<button id="btnLogout">退出登录</button>
<div id="user-info"></div>
<div id="orders-info"></div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var btnUserInfo = document.getElementById('btnUserInfo');
        var btnOrdersInfo = document.getElementById('btnOrdersInfo');
        var btnLogout = document.getElementById('btnLogout'); // 获取退出登录按钮
        var messageElement = document.getElementById("message");

        function getUserIDFromMessage() {
            const messageText = messageElement.textContent;
            const match = messageText.match(/用户ID：(\d+)/);
            return match ? parseInt(match[1], 10) : null;
        }

        btnUserInfo.addEventListener('click', function() {
            const userId = getUserIDFromMessage();
            if (userId) {
                fetchUserInfo(userId);
            } else {
                messageElement.textContent = "请先登录。";
            }
        });

        btnOrdersInfo.addEventListener('click', function() {
            const userId = getUserIDFromMessage();
            if (userId) {
                fetchOrders(userId);
            } else {
                messageElement.textContent = "请先登录。";
            }
        });

        btnLogout.addEventListener('click', function() {
            fetch('/api/users/logout', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (response.ok) {
                        // 清除客户端状态
                        clearClientState();
                        // 关闭当前窗口
                        window.close();
                        // 重定向到登录页面
                        window.open('index.html', '_blank');
                    } else {
                        console.error('Logout failed');
                        document.getElementById("message").textContent = "注销失败，请稍后重试或联系支持。";
                    }
                })
                .catch(error => {
                    console.error('Error during logout:', error);
                    document.getElementById("message").textContent = "注销过程中发生错误，请稍后重试或联系支持。";
                });
        });

        function fetchUserId() {
            fetch('/api/get-user-id', {
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch user ID');
                    }
                    return response.text();
                })
                .then(userId => {
                    if (userId === "not_logged_in") {
                        messageElement.textContent = "您还未登录，请先登录。";
                        document.getElementById("user-info").innerHTML = "";
                        document.getElementById("orders-info").innerHTML = "";
                    } else {
                        messageElement.textContent = "欢迎回来，用户ID：" + userId;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    messageElement.textContent = "登录状态获取失败，请刷新页面或重新登录。";
                });
        }

        function fetchUserInfo(userId) {
            fetch('/api/users/get-user-info?userId=' + userId, {
                credentials: 'include'
            })
                .then(response => response.json())
                .then(data => {
                    const userInfoDiv = document.getElementById("user-info");
                    userInfoDiv.innerHTML = `
                <h2>个人信息</h2>
                <p>Email: ${data.email}</p>
                <p>姓名: ${data.name}</p>
                <p>联系方式: ${data.contactInfo}</p>
            `;
                })
                .catch(error => {
                    console.error('Error fetching user info:', error);
                    document.getElementById("user-info").textContent = "获取个人信息失败。";
                });
        }

        function fetchOrders(userId) {
            fetch('/api/users/get-orders?userId=' + userId, {
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch orders');
                    }
                    return response.json();
                })
                .then(data => {
                    const ordersInfoDiv = document.getElementById("orders-info");
                    if (ordersInfoDiv) {
                        if (Array.isArray(data) && data.length > 0) {
                            ordersInfoDiv.innerHTML = `
                        <table>
                            <tr>
                                <th>订单ID</th>
                                <th>状态</th>
                                <th>总金额</th>
                                <th>操作</th>
                            </tr>
                            ${data.map(order => {
                                return `
                                <tr>
                                    <td>${order.orderID}</td>
                                    <td>${order.status}</td>
                                    <td>$${order.totalAmount}</td>
                                    <td>
                                        ${order.status === '未支付' ? `<button onclick="initiatePayment(${order.orderID})">支付</button>` : ''}
                                        <button onclick="deleteOrder(${order.id})">删除</button>
                                    </td>
                                </tr>
                                `;
                            }).join('')}
                        </table>
                        `;
                        } else {
                            ordersInfoDiv.textContent = "没有订单信息。";
                        }
                    } else {
                        console.error("订单信息容器未找到");
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById("orders-info").textContent = "获取订单信息失败。";
                });
        }

        function initiatePayment(orderId) {
            const userId = getUserIDFromMessage();
            if (userId) {
                fetch(`/api/orders/${orderId}/pay`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ userId: userId }),
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.text();
                    })
                    .then(data => {
                        // 支付宝的支付页面HTML代码会在这里返回
                        document.body.innerHTML = data;
                    })
                    .catch(error => {
                        console.error('支付请求失败:', error);
                    });
            } else {
                messageElement.textContent = "请先登录。";
            }
        }

        function deleteOrder(orderId) {
            if (!confirm('确定要删除这个订单吗？')) return;

            fetch(`/api/orders/${orderId}`, {
                method: 'DELETE',
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    fetchOrders(getUserIDFromMessage()); // 重新加载订单列表
                })
                .catch(error => {
                    console.error('Error deleting order:', error);
                });
        }

        function clearClientState() {
            // 清除客户端状态
            document.getElementById("user-info").innerHTML = "";
            document.getElementById("orders-info").innerHTML = "";
            messageElement.textContent = "";
            // 重定向到登录页面
            window.location.href = 'index.html';
        }

        fetchUserId();
    });
</script>
</body>
</html>